package com.moxiao.yfjh.module.activity.controller.app;

import com.moxiao.yfjh.framework.common.pojo.CommonResult;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.module.activity.common.ActivityNotifyMessageUtils;
import com.moxiao.yfjh.module.activity.controller.app.vo.AppActivityEnrollVerificatePageReqVO;
import com.moxiao.yfjh.module.activity.controller.app.vo.AppActivityVerificateVO;
import com.moxiao.yfjh.module.activity.controller.app.vo.AppVerificationMeltVo;
import com.moxiao.yfjh.module.activity.controller.app.vo.AppWriteOffVO;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityInfo.ActivityInfoDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityPackage.ActivityPackageDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityenrollverificate.ActivityEnrollVerificateDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.merchanType.MerchantTypeDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.merchantInfo.MerchantInfoDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.productInfo.ProductInfoDO;
import com.moxiao.yfjh.module.activity.service.activityInfo.ActivityInfoService;
import com.moxiao.yfjh.module.activity.service.activityPackage.ActivityPackageService;
import com.moxiao.yfjh.module.activity.service.activityVerificate.ActivityVerificateService;
import com.moxiao.yfjh.module.activity.service.activityenrollverificate.ActivityEnrollVerificateService;
import com.moxiao.yfjh.module.activity.service.merchanType.MerchantTypeService;
import com.moxiao.yfjh.module.activity.service.merchantInfo.MerchantInfoService;
import com.moxiao.yfjh.module.activity.service.productInfo.ProductInfoService;
import com.moxiao.yfjh.module.blind.dal.dataobject.member.BlindMemberUserDO;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.moxiao.yfjh.framework.common.pojo.CommonResult.success;
import static com.moxiao.yfjh.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "app - 相亲核销")
@RestController
@RequestMapping("/activity/verificate")
@Validated
public class AppActivityVerificateController {

    @Resource
    private ActivityVerificateService certificateService;
    @Resource
    private ActivityPackageService packageService;
    @Resource
    private ProductInfoService productInfoService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantTypeService merchantTypeService;
    @Resource
    private BlindMemberUserService memberService;
    @Resource
    private ActivityEnrollVerificateService enrollVerificateService;
    @Resource
    private ActivityNotifyMessageUtils messageUtils;
    @Resource
    private ActivityInfoService infoService;

    /**
     * 获得当前获得的核销码列表
     */
    @GetMapping("/getVerList")
    @Operation(summary = "获得当前获得的核销码列表")
    @Parameter(name = "activityId", description = "活动id")
    public CommonResult<List<AppVerificationMeltVo>> getVerList(@RequestParam(value = "activityId") Long activityId) {
        List<AppVerificationMeltVo> list = new ArrayList<>();
        ActivityInfoDO activityInfoDO = infoService.getInfo(activityId);
        if (Objects.nonNull(activityInfoDO)) {
            if (Objects.nonNull(activityInfoDO.getCostShare())) {
                // 费用分摊：非全款
                if (Objects.equals(activityInfoDO.getCostShare(),(byte) 1)) {
                    list = certificateService.getVerList(activityId, getLoginUserId());
                } else {
                    list = certificateService.getCreatorVerList(activityId, getLoginUserId());
                }
                list.forEach(item -> {
                    ProductInfoDO packageDO = productInfoService.getProductInfo(item.getProductsId());
                    if (Objects.nonNull(packageDO)) {
                        item.setProductName(packageDO.getName());
                    }
                    MerchantInfoDO merchantInfoDO = merchantInfoService.getMerchantInfo(item.getMerchantId());
                    if (Objects.nonNull(merchantInfoDO)) {
                        item.setMerchantName(merchantInfoDO.getName());
                        item.setMerchanAddress(merchantInfoDO.getAddress());
                        item.setMerchantCover(merchantInfoDO.getMerchantCover());
                        item.setMerchantCover(merchantInfoDO.getMerchantCover());
                    }
                });
            }
        }
        return success(list);
    }

    /**
     * 扫码-根据核销码查找对应的套餐/活动信息
     */
    @GetMapping("/getVerificationCode")
    @Operation(summary = "扫码-根据核销码查找对应的套餐/活动信息")
    @Parameter(name = "verificateCode", description = "核销码", required = true, example = "1024")
    public CommonResult<AppWriteOffVO> getPackage(@RequestParam("verificateCode") String verificateCode) {
        // app端返回对象
        AppWriteOffVO appActivityPackageVO = new AppWriteOffVO();
        // 通过核销码获得核销详情
        ActivityEnrollVerificateDO activityVerificateDO = certificateService.getCode(verificateCode);
        if (Objects.nonNull(activityVerificateDO)) {
            appActivityPackageVO.setId(activityVerificateDO.getId());
            appActivityPackageVO.setVerificationCode(activityVerificateDO.getVerificationCode());
            // 核销时间
            if (activityVerificateDO.getVerificationTime() != null) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedDateTime = activityVerificateDO.getVerificationTime().format(formatter);
                appActivityPackageVO.setVerificationTimes(formattedDateTime);
            }
            appActivityPackageVO.setStatus(activityVerificateDO.getStatus());
            if (Objects.nonNull(activityVerificateDO.getStatus()) && Objects.equals(activityVerificateDO.getStatus(),(byte) 0)) {
                appActivityPackageVO.setStatusName("未核销");
            }
            if (Objects.nonNull(activityVerificateDO.getStatus()) && Objects.equals(activityVerificateDO.getStatus(),(byte) 1)) {
                appActivityPackageVO.setStatusName("已核销");
            }
            //
            BlindMemberUserDO userDO = memberService.getMemberUser(activityVerificateDO.getUserId());
            if (Objects.nonNull(userDO)) {
                appActivityPackageVO.setNickname(userDO.getNickname());
                appActivityPackageVO.setUserNo(userDO.getNo());
            }
            // 商品信息
            ProductInfoDO productInfoDO = productInfoService.getProductInfo(activityVerificateDO.getActivityProductsId());
            if (Objects.nonNull(productInfoDO)) {
                appActivityPackageVO.setProductName(productInfoDO.getName());
                appActivityPackageVO.setProductIntro(productInfoDO.getProductIntroduct());
            }
            // 相亲活动套餐信息
            ActivityPackageDO packageInfo = packageService.getSelectOne(activityVerificateDO.getActivityId(), activityVerificateDO.getActivityProductsId());
            if (Objects.nonNull(packageInfo)) {
                // 查询商家信息
                if (packageInfo.getMerchantId() != null) {
                    MerchantInfoDO merchantInfo = merchantInfoService.getMerchantInfo(packageInfo.getMerchantId());
                    if (Objects.nonNull(merchantInfo)) {
                        // 商家信息
                        appActivityPackageVO.setName(merchantInfo.getName());
                        appActivityPackageVO.setAddress(merchantInfo.getAddress());
                        appActivityPackageVO.setMerchantIntro(merchantInfo.getMerchantIntro());
                        appActivityPackageVO.setMerchantCover(merchantInfo.getMerchantCover());
                        MerchantTypeDO merchantType = merchantTypeService.getMerchantType(merchantInfo.getMerchantType());
                        appActivityPackageVO.setMerchantTypeName(merchantType.getName());
                    }
                }
            }
            ActivityInfoDO info = infoService.getInfo(activityVerificateDO.getActivityId());
            if (Objects.nonNull(info)) {
                appActivityPackageVO.setActivityName(info.getName());
                appActivityPackageVO.setActiveDate(info.getActiveDate());
                appActivityPackageVO.setMenNum(info.getMenNum());
                appActivityPackageVO.setWomenNum(info.getWomenNum());
            }
        }
        return success(appActivityPackageVO);
    }

    /**
     * 通过id核销对应的核销码
     */
    @PutMapping("/updateWriteOff")
    @Operation(summary = "通过id核销对应的核销码")
    public CommonResult<Boolean> updateWriteOff(@Valid @RequestBody AppActivityVerificateVO updateReqVO) {
        // 通过核销码查找
        enrollVerificateService.updateStatus(updateReqVO.getId());

        ActivityEnrollVerificateDO verificate = enrollVerificateService.getEnrollVerificate(updateReqVO.getId());
        if (Objects.nonNull(verificate)) {
            ActivityInfoDO activityInfoDO = infoService.getInfo(verificate.getActivityId());
            if (Objects.nonNull(activityInfoDO)) {
                ActivityPackageDO packageInfo = packageService.getSelectOne(verificate.getActivityId(), verificate.getActivityProductsId());
                if (Objects.nonNull(packageInfo)) {
                    AppWriteOffVO appWriteOffVO = new AppWriteOffVO();
                    appWriteOffVO.setName(activityInfoDO.getName());
                    appWriteOffVO.setUserId(verificate.getUserId());
                    ProductInfoDO productInfoDO = productInfoService.getProductInfo(verificate.getActivityProductsId());
                    if (Objects.nonNull(productInfoDO)) {
                        appWriteOffVO.setProductName(productInfoDO.getName());
                    }
                    MerchantInfoDO merchantInfo = merchantInfoService.getMerchantInfo(packageInfo.getMerchantId());
                    if (Objects.nonNull(merchantInfo)) {
                        appWriteOffVO.setMerchantTypeName(merchantInfo.getName());
                        appWriteOffVO.setId(verificate.getId());
                        messageUtils.createVerificateMessage(appWriteOffVO);
                    }
                }
            }
        }
        return success(true);
    }

    /**
     * 商家-获得已核销（分页）
     */
    @GetMapping("/getMerchantPage")
    @Operation(summary = "商家-获得已核销（分页）")
    public CommonResult<PageResult<AppWriteOffVO>> getEnrollVerificatePage(@Valid AppActivityEnrollVerificatePageReqVO pageVO) {
        if (Objects.isNull(pageVO.getMerchantId())) {
            Long loginUserId = getLoginUserId();
            MerchantInfoDO longin = merchantInfoService.getLongin(loginUserId);
            if (Objects.nonNull(longin)) {
                pageVO.setMerchantId(longin.getId());
            }
        }

        PageResult<AppWriteOffVO> pageResult = enrollVerificateService.getMerchantVerificationList(pageVO);
        pageResult.getList().forEach(item -> {
            // 核销时间
            if (item.getVerificationTime() != null) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 指定日期格式
                String dateString = formatter.format(item.getVerificationTime());
                item.setVerificationTimes(dateString);
            }
            if (item.getStatus() != null && item.getStatus() == 0) {
                item.setStatusName("未核销");
            }
            if (item.getStatus() != null && item.getStatus() == 1) {
                item.setStatusName("已核销");
            }
            //
            BlindMemberUserDO userDO = memberService.getMemberUser(item.getUserId());
            if (Objects.nonNull(userDO)) {
                item.setNickname(userDO.getNickname());
                item.setUserNo(userDO.getNo());
            }
            // 商品信息
            ProductInfoDO productInfoDO = productInfoService.getProductInfo(item.getActivityProductsId());
            if (Objects.nonNull(productInfoDO)) {
                item.setProductName(productInfoDO.getName());
                item.setProductIntro(productInfoDO.getProductIntroduct());
                item.setProductCover(productInfoDO.getPlatformPrice());
            }
            // 相亲活动套餐信息
            ActivityPackageDO packageInfo = packageService.getSelectOne(item.getActivityId(), item.getActivityProductsId());
            if (Objects.nonNull(packageInfo)) {
                // 查询商家信息
                if (packageInfo.getMerchantId() != null) {
                    MerchantInfoDO merchantInfo = merchantInfoService.getMerchantInfo(packageInfo.getMerchantId());
                    if (Objects.nonNull(merchantInfo)) {
                        // 商家信息
                        item.setName(merchantInfo.getName());
                        item.setAddress(merchantInfo.getAddress());
                        item.setMerchantIntro(merchantInfo.getMerchantIntro());
                        item.setMerchantCover(merchantInfo.getMerchantCover());
                        MerchantTypeDO merchantType = merchantTypeService.getMerchantType(merchantInfo.getMerchantType());
                        item.setMerchantTypeName(merchantType.getName());
                    }
                }
            }
        });
        return success(pageResult);
    }
}
